package com.cow.framework.core.security;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;

import com.cow.framework.core.base.BaseComponent;
import com.cow.framework.core.config.constant.MessageConstants;
import com.cow.framework.core.exception.BusinessException;
import com.cow.support.dto.User;
import com.cow.support.entity.Resourceinfo;

/**
 * URL匹配校验
 * 
 * @author yangsj
 * */
@Component
public class UrlMather extends BaseComponent{
	private static Map<String,Resourceinfo> urlBlackList = new HashMap<String,Resourceinfo>();;
	
	public void checkUrl(String url){
		//检验是否存在于URL黑名单
		if(urlBlackList.get(url) == null) return;
						
		//权限认证		
		userAuth(url);
	}
	
	/**用户权限认证*/
	public void userAuth(String url){
		User user = super.getCurUser();
		//url匹配
		PathMatcher matcher = new AntPathMatcher();
		HashMap<String, List<Resourceinfo>> urlMap = user.getResourceMap();
		List<Resourceinfo> urlList = urlMap.get("2");		
		if(urlList != null && !urlList.isEmpty()){
			for(Resourceinfo r:urlList){				
				boolean result = matcher.match(r.getUrl(), url);  
				if(result) return;
			}
		}
		
		throw new BusinessException("B1100",MessageConstants.B1100);     
	}
	
	/**初始化URL黑名单*/
	@Scheduled(initialDelay=3000, fixedRate=3600000) 
    public void init(){
		//获取系统所有的URL资源黑名单
		List<Resourceinfo> urlList = hessianClient.getClient().getResourceByType(appName,"2");
		if(urlList != null && !urlList.isEmpty()){
			Map<String,Resourceinfo> urlMap = new HashMap<String,Resourceinfo>();
			for(Resourceinfo url:urlList){
				urlMap.put(url.getUrl(), url);
			}
			urlBlackList = urlMap;
		}		
	}
}


